package com.qiyu.tech.pay.controller;

import com.alibaba.fastjson.JSON;
import com.qiyu.core.cache.redis.app.lock.IDistributionLock;
import com.qiyu.tech.pay.dao.OrderInfoDao;
import com.qiyu.tech.pay.dao.WXPayConfigDao;
import com.qiyu.tech.pay.entity.OrderInfoPO;
import com.qiyu.tech.pay.entity.WXPayConfigPO;
import com.qiyu.tech.pay.queue.model.DelayTaskInfo;
import com.qiyu.tech.pay.queue.DelayTaskInfoManager;
import com.qiyu.tech.pay.queue.model.DelayTaskSortItem;
import com.qiyu.tech.pay.queue.RedisQueue;
import com.qiyu.tech.pay.service.UnionIdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.qiyu.tech.pay.constants.PayConfigConstants.DEFAULT_TIME_OUT;
import static com.qiyu.tech.pay.constants.PayConfigConstants.PAY_TOPIC;

/**
 * @Author linhao
 * @Date created in 10:39 下午 2021/4/3
 */
@RestController
@Slf4j
public class PayController {

    @Resource
    private WXPayConfigDao wxPayConfigDao;
    @Resource
    private RedisQueue<DelayTaskSortItem> redisDelayQueue;
    @Resource
    private DelayTaskInfoManager delayTaskInfoManager;
    @Resource
    private OrderInfoDao orderInfoDao;
    @Resource
    private UnionIdService unionIdService;
    @Resource
    private IDistributionLock iDistributionLock;


    @GetMapping(value = "doPay")
    public String doPay(int id){
        WXPayConfigPO wxPayConfigPO = wxPayConfigDao.getByPayConfigId(id);
        this.doWxPay(wxPayConfigPO);
        return "success";
    }

    /**
     * 模拟下微信的支付回调接口
     *
     * @param wxPayConfigPO
     */
    private void doWxPay(WXPayConfigPO wxPayConfigPO){
        //组装密钥，请求微信服务器
        log.info(" ========= request wx pay server ========= ");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String thirdNotifyUrl = wxPayConfigPO.getThirdNotifyUrl();
        RestTemplate restTemplate = new RestTemplate();
        //模拟微信的回调接口
        restTemplate.getForObject(thirdNotifyUrl,String.class);
    }

    @GetMapping(value = "wx-notify-url")
    public String wxNotifyUrl(HttpServletRequest request){
        log.info("get wx request success");
        String orderNo = request.getParameter("orderNo");
        String lockKey = "pay:notify:wx:lock" + orderNo;
        try {
            boolean lockStatus = iDistributionLock.tryLock(lockKey);
            if(!lockStatus) {
                throw new RuntimeException("try lock fail,key is " + lockKey);
            }
            OrderInfoPO orderInfoPO = orderInfoDao.getOrderInfoPO(orderNo);
            if(orderInfoPO == null){
                return "orderInfo not exist!";
            }
            DelayTaskInfo delayTaskInfo = new DelayTaskInfo();
            delayTaskInfo.setPayConfigId(orderInfoPO.getPayConfigId());
            delayTaskInfo.setTaskId(unionIdService.getUnionId());
            delayTaskInfo.setExecuteTime(System.currentTimeMillis());
            delayTaskInfo.setExecuteTimeout(System.currentTimeMillis() + DEFAULT_TIME_OUT);
            delayTaskInfo.setMessage(JSON.toJSONString(orderInfoPO));
            delayTaskInfo.setTopic(PAY_TOPIC);
            delayTaskInfo.setRetryTimes(0);
            DelayTaskSortItem delayTaskSortItem = new DelayTaskSortItem(delayTaskInfo.getTaskId(),PAY_TOPIC,delayTaskInfo.getExecuteTime());
            delayTaskInfoManager.put(delayTaskInfo.getTaskId(),delayTaskInfo);
            redisDelayQueue.put(delayTaskSortItem);
            return "wx-notify-success";
        }catch (Exception e){
            log.error("[wx-notify-url] has unKnow error , e is {}",e);
        }finally {
            iDistributionLock.releaseLock(lockKey);
        }
        return "unKnow Error";
    }

}
